<?php
/*
Name: Simple Image Gallery
Description: Allows the author of a site to create an image gallery
Version: 1.1.0
Author: Julian Castaneda (Square IT Solutions)
Author URI: http://www.squareitsol.com/
*/

# get correct id for plugin
$thisfile=basename(__FILE__, ".php");

//directory where we should store all the plugin related files
$plugin_folder_name = 'squareit-gallery';
$plugin_folder_path = GSPLUGINPATH.$plugin_folder_name.'/';
$rel_plugin_folder_path = substr(GSPLUGINPATH, strlen(GSROOTPATH)).$plugin_folder_name.'/';

//gallery settings file
$settings_file= $plugin_folder_path.'squareit_gallery.xml';

# register plugin
register_plugin(
	$thisfile,
	'Simple Image Gallery',
	'1.1.0',
	'Square IT Solutions',
	'http://www.squareitsol.com/',
	'Description: Allows the author of a site to create an image gallery',
	'plugins', //page type
	'squareit_setup_gallery'
);


//HOOKS
add_action('plugins-sidebar','createSideMenu',array($thisfile,'Simple Image Gallery'));
add_action('edit-extras','squareit_gallery_toggle',array());
add_action('changedata-save', 'squareit_gallery_toggle_save', array());
add_action('index-pretemplate','squareit_gallery_include_check',array());


/**
 * Creates and handles the gallery manager
 */
function squareit_setup_gallery()
{
	global $i18n;
	global $settings_file;
	$path = GSDATAUPLOADPATH;

	squareit_permissions_check();

	$count="0";
	$counter = "0";
	$totalsize = 0;
	$filesArray = array();
	$filenames = getFiles($path);
	
	//handle post request to save gallery
	if (isset($_POST['sqr_image']) && !empty($_POST['sqr_image'])) {
		$xml = @new SimpleXMLExtended('<?xml version="1.0" encoding="UTF-8"?><item></item>');
		
		$note = $xml->addChild('gallery_images');
		$note->addCData(implode('|', $_POST['sqr_image']));
	
		$xml->asXML($settings_file);
		
		squareit_msg_box('Image Gallery Saved Successfully!');
	}
	
	$sqr_images = squareit_get_gallery_images();
	
	if (count($filenames) != 0) {
		foreach ($filenames as $file) {
			if ($file == "." || $file == ".." || is_dir($path . $file) || $file == ".htaccess") {
				// not a upload file
			} else {
				$ext = substr($file, strrpos($file, '.') + 1);
				$extention = get_FileType($ext);
				if (strtolower($ext) == 'gif' || strtolower($ext) == 'jpg' || strtolower($ext) == 'jpeg' || strtolower($ext) == 'png')
				{
					$filesArray[$count]['name'] = $file;
					$filesArray[$count]['type'] = $extention;
					clearstatcache();
					$ss = @stat($path . $file);
					$filesArray[$count]['date'] = @date('M j, Y',$ss['ctime']);
					$filesArray[$count]['size'] = fSize($ss['size']);
					$totalsize = $totalsize + $ss['size'];
					$count++;
				}
			}
		}

		$filesSorted = subval_sort($filesArray,'name');
	}
	
	?>
	<label>Square It's Simple Image Gallery</label> <br/><br/>
	
	<?php if (!empty($filesSorted)) 
	{?>
	
		<p>Select the images you want to display in your image gallery. <br />
		<span style="color:#A1A1A1">To display the image gallery in a page, just go to the pages section, select the page you wish to edit and open up the "page options". Under page options you will see "Enable Image Gallery". Check this option and save the page</span></p>
		
		<form method="post" action="<?php echo $_SERVER ['REQUEST_URI']?>">
		<?php
	
		if (count($filesSorted) != 0) {
			echo '<table class="highlight" id="imageTable">';
			$count = 0;
			foreach ($filesSorted as $upload) {
				$counter++;
				if ($upload['type'] == $i18n['IMAGES']) {
					$cclass = 'iimage';
				} else {
					$cclass = '';
				}
				echo '<tr class="All '.$upload['type'].' '.$cclass.'" >';
				echo '<td class="imgthumb" style="display: table-cell;">';
				if ($upload['type'] == $i18n['IMAGES']) {
					$gallery = 'rel="facybox"';
					$pathlink = 'image.php?i='.$upload['name'];
					if (file_exists('../data/thumbs/thumbsm.'.$upload['name'])) {
						echo '<a href="../data/uploads/'. $upload['name'] .'" title="'. $upload['name'] .'" rel="facybox" ><img src="../data/thumbs/thumbsm.'.$upload['name'].'" /></a>';
					} else {
						echo '<a href="../data/uploads/'. $upload['name'] .'" title="'. $upload['name'] .'" rel="facybox" ><img src="inc/thumb.php?src='. $upload['name'] .'&dest=thumbsm.'. $upload['name'] .'&x=65&f=1" /></a>';
					}
				} else {
					$gallery = '';
					$controlpanel = '';
					$pathlink = $path . $upload['name'];
				}
	
				echo '</td><td><a title="'.$i18n['VIEW_FILE'].': '. $upload['name'] .'?" href="'. $pathlink .'" class="primarylink">'.$upload['name'] .'</a></td>';
				echo '<td style="width:70px;text-align:right;" ><span><b>'. $upload['size'] .'</span></td>';
				echo '<td style="width:70px;text-align:right;" ><span>'. $upload['date'] .'</span></td>';
				
				$checked = '';
				if (in_array($upload['name'], $sqr_images))
				{
					$checked = 'checked="checked"';
				}
				echo '<td style="text-align:right"><input type="checkbox" name="sqr_image[]" value="'.$upload['name'].'" '.$checked.'/></td>';
				//echo '<td ><input type="text" name="order" style="width:20px" /></td>';
				echo '</tr>';
				$count++;
			}
			echo '</table>';
			echo '<p><em><b>'. $counter .'</b> '.$i18n['TOTAL_FILES'].' ('. fSize($totalsize) .')</em></p>';
		} else {
			echo '<div id="imageTable"></div>';
		}
		?>
		<input type="submit" name="submit" class="submit" value="Save Image Gallery" /> 
		</form>
	<?php
	}
	else
	{
		squareit_msg_box('No images available.<br/> Click <a href="upload.php">here</a> to upload some images.');
	}

}

/**
 * Includes the gallery toggle checkbox into the edit page content section
 */
function squareit_gallery_toggle()
{
	global $data_edit;
	$checked = '';
	if (isset($data_edit->squareit_enable_gallery))
	{
		$checked = 'checked="checked"';
	}
	
	?>
	<tr>
		<td>
			<b>Enable Image Gallery?</b> 
			<input type="checkbox" name="sqr_enable_gallery" id="sqr_enable_gallery" value="1" <?php echo $checked;?>/>
		</td>
	</tr>
	<?php
}

/**
 * handles the gallery toggle save, and saves the status into the current page settings
 */
function squareit_gallery_toggle_save()
{
	global $xml;
	
	if (isset($_POST['sqr_enable_gallery']))
	{
		$note = $xml->addChild('squareit_enable_gallery');
		$note->addCData(1);
	}
}

/**
 *  Generates a message box
 *  - Prepare it so that it can be used across all square it plugins
 */
if (!function_exists('squareit_msg_box'))
{
	function squareit_msg_box($msg)
	{
		echo '<div style="width:98%; padding:5px; border:1px solid #FFE226; background-color:#FFF7C2; text-align:center; margin-bottom:5px;"> 
				'.$msg.' 
			 </div>';
	}
}

/**
 * Returns an array with all images in the gallery
 * 
 * @return array
 */
function squareit_get_gallery_images()
{
	global $settings_file;
	
	$sqr_images = array();
	if (file_exists($settings_file)) {
			$v = getXML($settings_file);
			$sqr_images = explode('|',$v->gallery_images);
	}
	
	return $sqr_images;
}

/**
 * Checks to see if the image gallery should be added to the current content page
 */
function squareit_gallery_include_check()
{
	global $data_index;
	
	if (!isset($data_index->squareit_enable_gallery))
	{
		return false;
	}
	
	add_action('theme-header','squareit_gallery_includes',array());
	add_action('content-bottom','squareit_include_gallery',array());
	
}

/**
 * Include the actual image gallery
 */
function squareit_include_gallery()
{
	global $plugin_folder_path;
	global $rel_plugin_folder_path;

	$sqr_images = squareit_get_gallery_images();
	$path = GSDATAUPLOADPATH;
	$thumbspath = $plugin_folder_path.'thumbs/';
	
	?>
	<!-- BEGIN Square IT's Simple Image Gallery -->
	<ul id="sqr_image_gallery">
		<?php 
		foreach ($sqr_images as $image) {
			$gallery = 'rel="facybox"';
			$pathlink = 'image.php?i='.$image;
			echo '<li><div>';
			if (file_exists($thumbspath.'thumbmed.'.$image)) {
				echo '<a href="data/uploads/'. $image .'" title="'. $image .'" rel="facybox" ><img src="'.$rel_plugin_folder_path.'thumbs/thumbmed.'.$image.'" class="sqr_img" /></a>';
			} else {
				echo '<a href="data/uploads/'. $image .'" title="'. $image .'" rel="facybox" ><img src="admin/inc/thumb.php?src='. $image .'&dest=../../'.$rel_plugin_folder_path.'thumbs/thumbmed.'. $image .'&x=125&y=125&f=1" class="sqr_img" /></a>';
			}
			echo '</div></li>';
		}?>
	
	</ul>
	<div class="sqr-clearer"></div>
	<script>
	jQuery(document).ready(function() { 
		$('a[rel*=facybox]').facybox();
		
	});
	
	$(window).load(function() {
		$('.sqr_img').vAlign();
	});
	
	(function ($) {
		// VERTICALLY ALIGN FUNCTION
		$.fn.vAlign = function() {
			return this.each(function(i){
				var ah = $(this).height();
				var ph = $(this).parent().parent().height();
				var mh = (ph - ah) / 2;
				$(this).css('margin-top', mh);
			});
		};
	})(jQuery);
	</script>
	<!-- END Square IT's Simple Image Gallery -->
	<?php 
}

/**
 *  include the CSS/JS file that are needed for the image gallery
 */
function squareit_gallery_includes()
{
	global $rel_plugin_folder_path;
	
	$jQuery = "admin/template/js/jquery.min.js";
	if (is_file(GSROOTPATH.'admin/template/js/jquery-1.4.1.min.js'))
	{
		$jQuery = "admin/template/js/jquery-1.4.1.min.js";
	}
	?>
	<script type="text/javascript" src="<?php echo $jQuery;?>"></script> 
	<script type="text/javascript" src="admin/template/js/facybox/jquery.facybox.js"></script>
	
	<link rel="stylesheet" type="text/css" href="admin/template/js/facybox/jquery.facybox.css">
	<link rel="stylesheet" type="text/css" href="<?php echo $rel_plugin_folder_path;?>sqr_imgal.css" media="all">
	<?php 
}


function squareit_permissions_check()
{
	global $plugin_folder_path;
	
	$thumbsPerm = substr(base_convert(fileperms($plugin_folder_path.'thumbs/'), 10, 8), 2);
	$plugPerm = substr(base_convert(fileperms($plugin_folder_path), 10, 8), 2);
	if ($plugPerm < 755)
	{
		$msg = 'Permissions to the plugin directory might not be set correctly. <br/><br/> <b>Path:</b> '.$plugin_folder_path.'<br/>';
		$msg .= '<b>Current Permissions:</b> '.$plugPerm.'<br/>';
		$msg .= '<b>Recommended Permissions:</b> 755';
		
		squareit_msg_box($msg);
	} 
	if ($thumbsPerm < 755)
	{
		$msg = 'Permissions to the plugin thumbs directory might not be set correctly. <br/><br/> <b>Path:</b> '.$plugin_folder_path.'thumbs/<br/>';
		$msg .= '<b>Current Permissions:</b> '.$thumbsPerm.'<br/>';
		$msg .= '<b>Recommended Permissions:</b> 755';
		squareit_msg_box($msg);
	}
}